package com.ruoyi.web.controller.system;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.QiniuCloudUtil;
import com.ruoyi.common.utils.file.MultipartFileToFile;
import com.ruoyi.system.domain.AppliDetail;
import com.ruoyi.system.domain.Formalities;
import com.ruoyi.system.service.IAppliDetailService;
import com.ruoyi.system.service.IFormalitiesService;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Qualification;
import com.ruoyi.system.service.IQualificationService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.ObjectInputFilter;

import javax.servlet.http.HttpServletResponse;

/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2021-04-29
 */
@RestController
@RequestMapping("/system/qualification")
public class QualificationController extends BaseController {
    @Autowired
    private IQualificationService qualificationService;
    @Autowired
    private IFormalitiesService formalitiesService;

    private String QiNiuYun ="http://jcx.greatforest.com.cn/";

    /**
     * 查询【请填写功能名称】列表
     */
//    @PreAuthorize("@ss.hasPermi('system:qualification:list')")
    @GetMapping("/list")
    public TableDataInfo list(Qualification qualification) {
        startPage();
        List<Qualification> list = qualificationService.selectQualificationList(qualification);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
//    @PreAuthorize("@ss.hasPermi('system:qualification:export')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Qualification qualification) {
        List<Qualification> list = qualificationService.selectQualificationList(qualification);
        ExcelUtil<Qualification> util = new ExcelUtil<Qualification>(Qualification.class);
        return util.exportExcel(list, "【请填写功能名称】数据");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:qualification:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(qualificationService.selectQualificationById(id));
    }

    /**
     * 新增【请填写功能名称】
     */
//    @PreAuthorize("@ss.hasPermi('system:qualification:add')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    @CrossOrigin
//    @RequestParam("multipartFiles") MultipartFile[] multipartFiles,
    public AjaxResult add(@Param("businessName") String businessName, @Param("EndTime")  Date EndTime, @RequestParam(value = "Files")MultipartFile[] Files, @RequestParam(value = "multipartFiles")MultipartFile[] multipartFiles, @RequestParam(value = "OtherFiles")MultipartFile[] OtherFiles) {
        Qualification qualification = new Qualification();
        qualification.setEndTime(EndTime);
        qualification.setBusinessName(businessName);
        String profile = RuoYiConfig.getProfile();
        try{
            //文件后缀
            if(multipartFiles.length>0) qualification.setQuaState(0); else qualification.setQuaState(1);
            if(Files.length>0)qualification.setLicenseState(0); else qualification.setLicenseState(1);
            if (qualificationService.insertQualification(qualification) == 1) {
                //新增资质
                if(multipartFiles.length>0) {
                    for (int i = 0; i < multipartFiles.length; i++) {
                        File file1 = MultipartFileToFile.MultipartFileToFile(multipartFiles[i]);
                        String name = multipartFiles[i].getOriginalFilename().substring(0,multipartFiles[i].getOriginalFilename().indexOf("."));
                        String substring = multipartFiles[i].getOriginalFilename().substring(multipartFiles[i].getOriginalFilename().indexOf("."));
                        String filename = name+"("+qualification.getId()+")"+substring;
                        QiniuCloudUtil.upload(file1, filename);
                        Formalities formalities = new Formalities();
                        formalities.setQualiId(qualification.getId());
                        formalities.setCreatTime(new Date());
                        formalities.setForName("资质");
                        formalities.setUrl(QiNiuYun + filename);
                        formalitiesService.insertFormalities(formalities);
                        file1.delete();
                    }
                }
                //新增营业执照
                if(Files.length>0) {
                    for (int i = 0; i < Files.length; i++) {
                        File file1 = MultipartFileToFile.MultipartFileToFile(Files[i]);
                        String name = Files[i].getOriginalFilename().substring(0,Files[i].getOriginalFilename().indexOf("."));
                        String substring = Files[i].getOriginalFilename().substring(Files[i].getOriginalFilename().indexOf("."));
                        String filename = name+"("+qualification.getId()+")"+substring;
                        QiniuCloudUtil.upload(file1, filename);
                        Formalities formalities = new Formalities();
                        formalities.setQualiId(qualification.getId());
                        formalities.setCreatTime(new Date());
                        formalities.setForName("营业执照");
                        formalities.setUrl(QiNiuYun + filename);
                        formalitiesService.insertFormalities(formalities);
                        file1.delete();
                    }
                }
                if (OtherFiles.length> 0) {
                    for (int i = 0; i < OtherFiles.length; i++) {
                        byte[] bytes = OtherFiles[i].getBytes();
                        //文件夹
                        Path path2 = Paths.get(profile + "//File//" + qualification.getId());
                        //具体文件
                        Path path = Paths.get(profile + "//File//" + qualification.getId() + "//" + OtherFiles[i].getOriginalFilename());
                        File file1 = path.toFile();
                        if (!file1.exists()) {
                            path2.toFile().mkdirs();
                        }
                        if (file1.isFile()) {
                            file1.delete();
                        } else {
                            java.nio.file.Files.write(path, bytes);//创建文件
                        }
                        Formalities formalities = new Formalities();
                        formalities.setQualiId(qualification.getId());
                        formalities.setCreatTime(new Date());
                        formalities.setForName("其他资料");
                        formalities.setUrl( "/profile/File/" + qualification.getId() +"/"+ OtherFiles[i].getOriginalFilename());
                        formalitiesService.insertFormalities(formalities);
                    }
                    return AjaxResult.success(qualificationService.selectQualificationById(qualification.getId()));
                }
            }
            return AjaxResult.success(qualificationService.selectQualificationById(qualification.getId()));
        } catch (Exception e) {
            qualificationService.deleteQualificationById(qualification.getId());
            return AjaxResult.error();
        }
    }

    /**
     * 修改【请填写功能名称】
     */
//    @PreAuthorize("@ss.hasPermi('system:qualification:edit')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    @CrossOrigin
    public AjaxResult edit(@Param("id")Long id,@Param("businessName") String businessName, @Param("EndTime")  Date EndTime, @RequestParam(value = "Files")MultipartFile[] Files, @RequestParam(value = "multipartFiles")MultipartFile[] multipartFiles, @RequestParam(value = "OtherFiles")MultipartFile[] OtherFiles){
        try {
            Qualification qualification = new Qualification();
            qualification.setId(id);
            qualification.setBusinessName(businessName);
            qualification.setEndTime(EndTime);
            String profile = RuoYiConfig.getProfile();
            if (multipartFiles.length > 0) qualification.setQuaState(0);
            else qualification.setQuaState(1);
            if (Files.length > 0) qualification.setLicenseState(0);
            else qualification.setLicenseState(1);
            if (qualificationService.updateQualification(qualification) == 1) {
//                删除
                qualificationService.deleteFormalitiesByqualiId(qualification.getId());
                //新增资质
                if (multipartFiles.length > 0) {
                    for (int i = 0; i < multipartFiles.length; i++) {
                        File file1 = MultipartFileToFile.MultipartFileToFile(multipartFiles[i]);
                        String name = multipartFiles[i].getOriginalFilename().substring(0,multipartFiles[i].getOriginalFilename().indexOf("."));
                        String substring = multipartFiles[i].getOriginalFilename().substring(multipartFiles[i].getOriginalFilename().indexOf("."));
                        String filename = name+qualification.getId()+substring;
                        QiniuCloudUtil.upload(file1, filename);
                        Formalities formalities = new Formalities();
                        formalities.setQualiId(qualification.getId());
                        formalities.setCreatTime(new Date());
                        formalities.setForName("资质");
                        formalities.setUrl(QiNiuYun + filename);
                        formalitiesService.insertFormalities(formalities);
                        file1.delete();
                    }
                }
                //新增营业执照
                if (Files.length > 0) {
                    for (int i = 0; i < Files.length; i++) {
                        File file1 = MultipartFileToFile.MultipartFileToFile(Files[i]);
                        String name = Files[i].getOriginalFilename().substring(0,Files[i].getOriginalFilename().indexOf("."));
                        String substring = Files[i].getOriginalFilename().substring(Files[i].getOriginalFilename().indexOf("."));
                        String filename = name+"("+qualification.getId()+")"+substring;
                        QiniuCloudUtil.upload(file1, filename);
                        Formalities formalities = new Formalities();
                        formalities.setQualiId(qualification.getId());
                        formalities.setCreatTime(new Date());
                        formalities.setForName("营业执照");
                        formalities.setUrl(QiNiuYun + filename);
                        formalitiesService.insertFormalities(formalities);
                        file1.delete();
                    }
                }
                if (OtherFiles.length> 0) {
                    for (int i = 0; i < OtherFiles.length; i++) {
                        byte[] bytes = OtherFiles[i].getBytes();
                        //文件夹
                        Path path2 = Paths.get(profile + "//File//" + qualification.getId());
                        //具体文件
                        Path path = Paths.get(profile + "//File//" + qualification.getId() + "//" + OtherFiles[i].getOriginalFilename());
                        File file1 = path.toFile();
                        if (!file1.exists()) {
                            path2.toFile().mkdirs();
                        }
                        if (file1.isFile()) {
                           file1.delete();
                        } else {
                            java.nio.file.Files.write(path, bytes);//创建文件
                        }
                        Formalities formalities = new Formalities();
                        formalities.setQualiId(qualification.getId());
                        formalities.setCreatTime(new Date());
                        formalities.setForName("其他资料");
                        formalities.setUrl( "/profile/File/" + qualification.getId() +"/"+ OtherFiles[i].getOriginalFilename());
                        formalitiesService.insertFormalities(formalities);
                    }

                }
                return AjaxResult.success(qualificationService.selectQualificationById(qualification.getId()));
            }
        }catch (Exception e){
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

    /**
     * 删除【请填写功能名称】
     */
//    @PreAuthorize("@ss.hasPermi('system:qualification:remove')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(qualificationService.deleteQualificationByIds(ids));
    }

    @Autowired
    private IAppliDetailService appliDetailService;

    //器具导出
    @PostMapping("/uplod")
    @CrossOrigin
    public void uplod(Long id,HttpServletResponse response){
        try {
            AppliDetail appliDetail = appliDetailService.queryAppliDetailListById(id);
            List<Object> list = new ArrayList<>();
            // 表一数据
            SimpleDateFormat simpleDateFormat= new SimpleDateFormat( "yyyy-MM-dd");
            for (int i = 0; i < appliDetail.getAppliDetailMats().size(); i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", i+1);
                map.put("appliName", appliDetail.getAppliDetailMats().get(i).getAppliName());
                map.put("appliSpecifications", appliDetail.getAppliDetailMats().get(i).getAppliSpecifications());
                map.put("appliModle", appliDetail.getAppliDetailMats().get(i).getAppliModle());
                if(null!=appliDetail.getAppliDetailMats().get(i).getAppliUnit())map.put("appliUnit", appliDetail.getAppliDetailMats().get(i).getAppliUnit());
                if(null!=appliDetail.getAppliDetailMats().get(i).getAppliBusiness())map.put("appliBusiness", appliDetail.getAppliDetailMats().get(i).getAppliBusiness());
                if (null!=appliDetail.getAppliDetailMats().get(i).getAppliIsCommon()){
                    if (appliDetail.getAppliDetailMats().get(i).getAppliIsCommon().equals("0")) map.put("commBus", "否");
                    if (appliDetail.getAppliDetailMats().get(i).getAppliIsCommon().equals("1")) map.put("commBus", "是");
                }else map.put("appliIsCommon","");
                map.put("appliSum", appliDetail.getAppliDetailMats().get(i).getAppliSum());
                if (null!=appliDetail.getAppliDetailMats().get(i).getAppliStartTime())
                    map.put("appliStartTime",simpleDateFormat.format( appliDetail.getAppliDetailMats().get(i).getAppliStartTime()));
                if (null!=appliDetail.getAppliDetailMats().get(i).getAppliEndTime())
                    map.put("appliEndTime",simpleDateFormat.format(  appliDetail.getAppliDetailMats().get(i).getAppliEndTime()));
                if (null!= appliDetail.getAppliDetailMats().get(i).getUseDay())
                    map.put("useDay", appliDetail.getAppliDetailMats().get(i).getUseDay());
                if (null!= appliDetail.getAppliDetailMats().get(i).getAppliPrice())
                    map.put("appliPrice","￥"+ appliDetail.getAppliDetailMats().get(i).getAppliPrice());
                if (null!= appliDetail.getAppliDetailMats().get(i).getSum())
                    map.put("sum", "￥"+appliDetail.getAppliDetailMats().get(i).getSum());
                if (null!= appliDetail.getAppliDetailMats().get(i).getAppliRemark())
                    map.put("appliRemark", appliDetail.getAppliDetailMats().get(i).getAppliRemark());
                list.add(map);
            }
            // 表格使用的数据
            Map map = new HashMap();
            map.put("proName", appliDetail.getProName());
            map.put("proNumber", appliDetail.getProNumber());
            map.put("deliveryReq", appliDetail.getDeliveryReq());
            map.put("requisitionDate", simpleDateFormat.format( appliDetail.getRequisitionDate()));
            map.put("data", list);//放入表一数据
            if (null!=appliDetail.getFullAmount())
                map.put("fullAmount", "￥"+appliDetail.getFullAmount());//放入表一数据
            for (int i = list.size(); i < 20; i++) {
                Map<String, Object> map1 = new HashMap<>();
                map1.put("id", list.size() + 1);
                map1.put("mName", "");
                map1.put("name", "");
                map1.put("mUnit", "");
                map1.put("mdBrand", "");
                map1.put("mdBusiness", "");
                map1.put("commBus", "");
                map1.put("mdSum", "");
                map1.put("mdPrice", "");
                map1.put("sum", "");
                list.add(map1);
            }
            // 获取模板文件
            //读取模板
            TemplateExportParams params = new TemplateExportParams("/home/ruoyi/excel/租赁采购申请单.xlsx");
            Workbook workbook = ExcelExportUtil.exportExcel(params, map);
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
